import React, { useState, useEffect } from 'react';
import classnames from 'classnames';
import moment from 'moment';
import { connect } from 'dva';
import { Button, Form, Select, Table, Empty, Modal, message, Tag } from 'antd';
import TPage from '@/modules/TPage';
import CreateModal from './modules/CreateModal';
import Service from '@/public/http/services';
import { GoodsClassify, FictitiousGoodsType, GoodsType } from '@/public/constant/enums';
import style from './index.css';
const { Option } = Select;
const { Column } = Table;
const List: React.FC<any> = ({ total, list,specs, dispatch }) => {
  const [curPage, setCurPage] = useState(1);
  const [curNickName, setCurNickName] = useState(null);
  const pageSize = 10;
  /**
   * 加载列表数据
   */
  function fetchList({ page, nickname }) {
    dispatch({
      type: 'goodsManagement/fetchList',
      payload: {
        page,
        nickname,
        pageSize
      }
    })
  }

  /**
   * @desc 操作完更新列表
   */
  function reFetchList() {
    fetchList({
      page: curPage,
      nickname: curNickName
    })
  }


  useEffect(({ page = curPage, nickname = curNickName } = {}) => {
    fetchList({ page, nickname })
  }, [curPage, curNickName])
  // 渲染列表查询表单

  const handleQuery = (query) => {
    setCurPage(1);
    setCurNickName(query);
  }

  function renderTableForm() {
    const WrappedForm = Form.create<any>({ name: 'tableForm' })(function ({ form }) {
      const { getFieldDecorator } = form as any;
      return (
        <Form onSubmit={handleQuery.bind(null, form)} layout={'inline'}>

        </Form>
      );
    })
    return (
      <WrappedForm />
    );
  }

  // 根据渲染类型渲染列表
  const renderActions =
    (record: any) => {
      const { status, type } = record;
      return (
        status === 0 ?
        <>
          <Button className={style.mr8} type={'primary'} onClick={() => { handleEdit(record) }}>编辑</Button>
          <Button className={style.mr8} onClick={() => { handleSetHomeGoods(record) }}>设置首页商品</Button>
          <Button className={style.mr8} onClick={() => { handleOffOrOnline(record) }}>上架</Button>
          <Button className={style.mr8} type={'danger'} onClick={() => { handleDelete(record) }}>删除</Button>
        </> :
        <Button className={style.mr8} onClick={() => { handleOffOrOnline(record) }}>下架</Button>
      );
    }

  const [formModalVisible, setFormModalVisible] = useState(false);
  const [curModalStatus, setCurModalStatus] = useState(0);

  /**
   *
   * @desc 创建
   */
  const handleCreate = () => {
    setCurModalStatus(0);
    setFormModalVisible(true);
    setCurEditInfo({});
  }

  const [curEditInfo, setCurEditInfo] = useState({})
  /**
   *
   * @desc 编辑
   */
  const handleEdit = (record) => {
    setCurModalStatus(1);
    setCurEditInfo(record);
    setFormModalVisible(true);
  }

  /**
   * @desc 创建提交
   */
  const handleSubmit = (form: any, { files, description,curGroup,curSKUList }, status) => {
    const { validateFields, resetFields } = form;
    validateFields((err, value) => {
      if (!err) {
        let groupIds = ''
        for(let i=0;i<curGroup.length;i++){
          if(i!=0){
            groupIds += ','
          }
          groupIds += curGroup[i]
        }


        const imgs = files.map((file) => file.url).join(',');
        const { cid, type, title, virtualAddress, price } = value;
        const params = { cid, type, description, title, virtualAddress, price, imgs,groupIds:groupIds,skuInfoList:curSKUList };
        (status ? Service.createGoodsInfo(params) : Service.updateGoodsInfo({ id: curEditInfo['id'], ...params })).then(() => {
          message.info(`${type ? '添加' : '修改'}成功`);
          resetFields();
          setCurEditInfo({});
          setFormModalVisible(false);
          reFetchList();
        })
      }
    })
  }

  /**
   * @desc 商品规格配置
   */
  const handleSkuConfig = (record) => {

  }

  /**
   * @desc 设置首页商品
   * @param param0
   */
  const handleSetHomeGoods = ({id}) => {
    Modal.confirm({
      title: '确定要将该商品设置为首页商品？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        Service.setHomeGoods({
          id
        }).then(() => {
          message.info('设置成功');
          reFetchList();
        })
      }
    });
  }

  /**
   *
   * @desc 创建/编辑取消
   */
  const handleCancel = (form) => {
    form.resetFields();
    setCurEditInfo({});
    setFormModalVisible(false);
  }

  /**
   * @desc 删除
   */
  const handleDelete = ({ id }) => {
    Modal.confirm({
      title: '确定要将该商品信息删除吗？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Service.deleteGoodById({
          id
        }).then(() => {
          message.info('删除成功');
          reFetchList();
        })
      }
    });
  }

  /**
   * @desc 商品上下架
   * @param id
   */
  const handleOffOrOnline = ({id, status}) => {
    Modal.confirm({
      title: `确定要${status? '下架': '上架'}该商品信息吗？`,
      okText: status? '下架': '上架',
      okType: 'primary',
      cancelText: '取消',
      onOk: () => {
        (status ? Service.offlineGoodsStatus : Service.onlineGoodsStatus)({
          id
        }).then(() => {
          message.info(`${status? '下架': '上架'}成功`);
          reFetchList();
        })
      }
    });
  }


  return (
    <TPage>
      <TPage.Title>商品库管理列表</TPage.Title>
      <TPage.Table>
        <TPage.Layout className={style.action_block}>
          <Button type={'primary'} onClick={handleCreate}>新建</Button>
          <TPage.Search
            placeholder={'请输入商品名称，可按回车键搜索'}
            onSearch={handleQuery}
          />
        </TPage.Layout>
        <TPage.Layout>
          {renderTableForm()}
        </TPage.Layout>
        <Table
          className={classnames(style.mt16, style.expert_list)}
          locale={{ emptyText: <Empty description={'无数据'} /> }}
          scroll={{ x: 1440}}
          dataSource={list}
          pagination={{ total, current: curPage, pageSize, onChange: setCurPage }}
          rowKey={(record: any) => record.id}
        >
          <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
          <Column title={'商品名称'} key={'username'}
            render={(value, record: any) => {
              return <span className={style.thumbnail}>
                < img src={record.imgs.split(',')[0]} />
                {record.title}
              </span>
            }}
          />
          <Column title={'所属分类'} dataIndex={'type'} key={'type'} render={(value) => <Tag color={value ? 'volcano' : 'cyan'}>{GoodsClassify[value]}</Tag>} />
          <Column title={'所属类目'} dataIndex={'cid'} key={'cid'} render={(value, record: any) => (record.type ? FictitiousGoodsType: GoodsType)[value]}/>
          <Column title={'价格(元)'} dataIndex={'price'} key={'price'} />
          <Column title={'商品状态'} dataIndex={'status'} key={'status'} render={value => <span className={value ? style.online : style.default}>{value ? '上架' : '下架'}</span>}/>
          <Column title={'更新时间'} dataIndex={'updateTime'} key={'updateTime'} render={(value) => value && moment(value).format('YYYY-MM-DD hh:mm:ss')} />
          <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} render={(value) => value && moment(value).format('YYYY-MM-DD hh:mm:ss')} />
          <Column title={'操作'} key={'act'} fixed={'right'} render={renderActions} />
        </Table>
      </TPage.Table>
      <CreateModal visible={formModalVisible}
        title={curModalStatus === 0 ? '商品创建' : '商品编辑'}
        formData={curModalStatus === 0 ? {} : curEditInfo}
                   specs={specs}
        onOK={(form, data) => handleSubmit(form, data, curModalStatus === 0)}
        onCancel={handleCancel} />
    </TPage>
  );
}
export default connect((state: any) => {
  return {
    list: state.goodsManagement.list,
    total: state.goodsManagement.total,
    specs:state.goodsManagement.specs,
  };
})(List);
